package logic

import (
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"context"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserFileListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserFileListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFileListLogic {
	return &UserFileListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserFileListLogic) UserFileList(req *types.UserFileListRequest, userIdentity string) (resp *types.UserFileListResponse, err error) {
	resp = new(types.UserFileListResponse)
	size := req.Size
	if size == 0 {
		size = l.svcCtx.Config.PageSize
	}

	page := req.Page
	if page == 0 {
		page = 1
	}
	page = (page - 1) * size

	urs, err := l.svcCtx.UserRepostioryModel.GetUserFilesList(req.Id, userIdentity, size, page)
	if err != nil {
		resp.Message = "获取失败" + err.Error()
		resp.Code = 100
		return resp, nil
	}

	ufs := make([]*types.UserFile, 0)
	for _, ur := range urs {
		rep, _, err := l.svcCtx.RepositoryPoolModel.GetRepositoryPoolByIdentity(ur.ReoisitoryIdentity)
		if err != nil {
			continue
		}

		uf := &types.UserFile{
			Id:                 int64(ur.Id),
			IdentityId:         ur.Identity,
			ReoisitoryIdentity: ur.ReoisitoryIdentity,
			Ext:                ur.Ext,
			Path:               rep.Path,
			Name:               ur.Name,
			Size:               int(rep.Size),
		}
		ufs = append(ufs, uf)
	}
	resp.Message = "获取成功"
	resp.Code = 200
	fileCount, _ := l.svcCtx.UserRepostioryModel.GetUserFileCount(req.Id, userIdentity)
	resp.Count = fileCount
	resp.Data = ufs
	return
}
